/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ec.medical.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrador
 */
public class EncriptacionUtil {
    private static Logger LOG = Logger.getLogger(EncriptacionUtil.class.getName());
    
    //algoritmos
    public static String MD2 = "MD2";
    public static String MD5 = "MD5";
    public static String SHA1 = "SHA-1";
    public static String SHA256 = "SHA-256";
    public static String SHA384 = "SHA-384";
    public static String SHA512 = "SHA-512";

    private static String toHexadecimal(byte[] digest) {
        String hash = "";
        for (byte aux : digest) {
            int b = aux & 0xff;
            if (Integer.toHexString(b).length() == 1) {
                hash += "0";
            } 
            hash += Integer.toHexString(b);
        }
        return hash;
    }

    private static String getStringMessageDigest(String message, String algorithm) {

        byte[] digest = null;
        byte[] buffer = message.getBytes();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.reset();
            messageDigest.update(buffer);
            digest = messageDigest.digest();
        } catch (NoSuchAlgorithmException ex) {
            System.out.println("Error creando Digest");
        }
        return toHexadecimal(digest);
    }

    /**
     * Metodo que encripta un texto utilizando el algoritmo MD5
     * @param valor
     * @return
     */
    public static String encriptarMD5(String valor) {
        String valorEncriptado = EncriptacionUtil.getStringMessageDigest(valor, EncriptacionUtil.MD5);
        LOG.info("valorEncriptado=  " + valorEncriptado);
        return valorEncriptado;
    }
}
